package dao

import (
	"context"
	"database/sql"
	"errors"
	"tcp_server/src/config"
	"tcp_server/src/models"
	"time"
)

// GetUserByUsername 通过用户名查询用户 的账号密码
func GetUserByUsername(userName string) (*models.User, error) {
	query := "SELECT user_name, password FROM t_user WHERE user_name = ?"
	row := config.Mysql.QueryRow(query, userName)

	user := &models.User{}
	err := row.Scan(&user.UserName, &user.Password)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil // 用户不存在
		}
		return nil, err // 其他数据库错误
	}
	return user, nil
}

func UpdateToken(userName string, token string, expireTime time.Time) error {
	query := `
        INSERT INTO t_token (user_name, token, expire_time)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE
            token = VALUES(token),
            expire_time = VALUES(expire_time);
    `

	// 执行 SQL 语句
	_, err := config.Mysql.ExecContext(context.Background(), query, userName, token, expireTime)
	return err
}

func UpdateUserBaseMessage(user *models.User) error {
	query := `update t_user set nick_name = ? , picture = ? where user_name = ?`
	_, err := config.Mysql.ExecContext(context.Background(), query, user.NickName, user.Picture, user.UserName)
	return err
}

// GetUserBaseMessage 通过用户名查询用户 的基本信息 nickname 和 picture
func GetUserBaseMessage(username string) (*models.User, error) {
	query := `select nick_name, picture from t_user where user_name = ? and delete_flag = 0`
	row := config.Mysql.QueryRow(query, username)
	user := &models.User{}
	err := row.Scan(&user.NickName, &user.Picture)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil // 用户不存在
		}
		return nil, err // 其他数据库错误
	}
	return user, err
}
